package fun.fykj.liu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.fykj.liu.dto.ManagerOut;
import fun.fykj.liu.entity.User;
import fun.fykj.liu.mapper.UserMapper;
import fun.fykj.liu.model.Result;
import fun.fykj.liu.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author DongJin
 * @since 2020-01-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Result getManager() {
        //获取当周管理员
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        User thisManager = baseMapper.selectOne(wrapper);
        //获取下周管理员
        QueryWrapper<User> nextWrapper = new QueryWrapper<>();
        nextWrapper.eq("status", 2);
        User nextManager = baseMapper.selectOne(nextWrapper);
        ManagerOut managerOut = new ManagerOut();
        if (null != thisManager && null != thisManager.getName())
            managerOut.setThisWeek(thisManager.getName());
        if (null != nextManager && null != nextManager.getName())
            managerOut.setNextWeek(nextManager.getName());
        return Result.ok(managerOut);
    }

    @Override
    @Transactional
    public boolean changeManager() {
        ArrayList<User> list = new ArrayList<>();
        //查找下周管理员
        User newNextManager = baseMapper.getNextManager();
        if (null == newNextManager)
            newNextManager = baseMapper.getFirstUser();
        //设置下周管理员
        newNextManager.setStatus(2);
        //获取下周管理员
        QueryWrapper<User> nextWrapper = new QueryWrapper<>();
        nextWrapper.eq("status", 2);
        User newThisManager = baseMapper.selectOne(nextWrapper);
        newThisManager.setStatus(1);
        //还原上周管理员
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        User oldThisManager = baseMapper.selectOne(wrapper);
        oldThisManager.setStatus(0);
        list.add(newNextManager);
        list.add(newThisManager);
        list.add(oldThisManager);
        boolean b = updateBatchById(list);
        return b;
    }
}
